package ch.ffhs.radarpp;

import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import ch.ffhs.radarpp.managers.WebRequestManager;
import ch.ffhs.radarpp.misc.BaseActivity;
import ch.ffhs.radarpp.model.Friend;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

/**
 * Zeigt einen bestimmten Freund auf der Karte an
 * @author Fabian
 *
 */
public class MapsActivity extends BaseActivity {

	private Friend friend;
	private Marker marker;
	private GoogleMap map;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_maps);

		map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

		friend = (Friend) getIntent().getExtras().getSerializable(getString(R.string.serializable_friend));
		MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(friend.lastLocation().getLatitude(), friend.lastLocation().getLongitude())).title(friend.getName());
		map.setMyLocationEnabled(true);
		
		marker = map.addMarker(markerOptions);
		
		zoomToMarker();
		setActionbarBackbuttonAsVisible();
	}

	private void zoomToMarker(){

		CameraPosition cameraPosition = new CameraPosition.Builder().target(marker.getPosition()).zoom(17).tilt(30).build();
		map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

	}
	
	@Override
	protected void onResume() {
		super.onResume();

		startTimerTaks(new TimerTask() {

			@Override
			public void run() {
				getWebManager().executeHTTPRequest(WebRequestManager.createGetFriendsLocationRequest(MapsActivity.this, friend.getUserid()));
			}
		});

	}

	@Override
	protected void onPause() {
		stopTimer();
		super.onPause();
	}
	
	@Override
	public void requestCompleted(String result, Object context) {
		try {

			JSONObject o = new JSONObject(result);

			LatLng newPosition = new LatLng(o.getDouble(getString(R.string.getfriendslocationresult_lat)), o.getDouble(getString(R.string.getfriendslocationresult_long)));
			marker.setPosition(newPosition);
		
			zoomToMarker();
			
		} catch (JSONException ex) {
			ex.printStackTrace();
		}
	}

}
